import { Context, Next } from "koa";
import errors from "../common/errors";
import { getTime } from "../utils/time";

// 请求封装，同时处理返回结果、异常错误等
export default () => async (ctx: Context, next: Next) => {
  // 处理默认图标
  if (ctx.url === "/favicon.ico") {
    ctx.status = 404;
    return;
  }

  const startTime = Date.now();

  // 合并参数
  ctx.reqParams = { ...ctx.query, ...ctx.request.body };

  // 执行请求
  try {
    const data = await next();
    if (ctx.body === undefined) {
      ctx.body = { code: 0, data };
    }

    // TODO: 添加日志
    const duration = Date.now() - startTime;

    console.log(`【Request】[${getTime()}] [${ctx.method}] ${ctx.url} [${duration}ms]`);
  } catch (e) {
    // 格式化错误返回
    let [code, errMsg] = (e.message || "").split("::");
    if (!errMsg) {
      const defaultErrorMsg = errors[code as keyof typeof errors];
      if (defaultErrorMsg) {
        errMsg = defaultErrorMsg;
      } else {
        errMsg = code;
        code = "UNKNOWN";
      }
    }

    ctx.body = { code, message: errMsg };

    const duration = Date.now() - startTime;

    // TODO: 添加错误日志
    console.log(`【Error Request】 [${getTime()}] [${ctx.method}] ${ctx.url} [${duration}ms] [ErrorMsg: ${JSON.stringify(ctx.body)}] ${(e.stack || "")}`);
  }
};
